package demo.kk;

public class OrderingDemo {

    private int x = 0;
    private int y = 0;
    private boolean ready = false;

    public void writer() {
        x = 100; // 操作1
        y = 200; // 操作2
        ready = true; // 操作3 - 标志位，表示数据已准备好
    }

    public void reader() {
        if (ready) { // 操作4 - 如果数据已准备好，则读取
            // 由于缺乏同步，操作1和2可能看起来在操作3之后才发生
            System.out.println("x: " + x + ", y: " + y); // 可能输出 x: 0, y: 0 或其它意外结果
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final OrderingDemo demo = new OrderingDemo();

        // 线程A：执行写操作
        Thread threadA = new Thread(demo::writer);

        // 线程B：执行读操作
        Thread threadB = new Thread(demo::reader);

        threadA.start();
        threadB.start();

        threadA.join();
        threadB.join();
    }
}